package main

import (
	"io"
	"os"

	fileviewplugin "gitee.com/liuxyz/file-view-plugin"
	"github.com/gin-gonic/gin"
)

func NewPlugin() fileviewplugin.Plugin {
	return TextPreview{}
}

type TextPreview struct{}

func (t TextPreview) Name() string {
	return "text-preview"
}

func (t TextPreview) ExportRouter() map[string]gin.HandlerFunc {
	return map[string]gin.HandlerFunc{
		"/ReadTextFile": ReadTextFile,
	}
}

func ReadTextFile(ctx *gin.Context) {
	type request struct {
		FileName string `json:"fileName"`
	}

	var req request
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(400, gin.H{"error": err.Error()})
		return
	}

	// os.OpenFile(req.FileName, flag int, perm FileMode)
	f, err := os.OpenFile(req.FileName, os.O_RDONLY, 0o666)
	if err != nil {
		ctx.JSON(500, gin.H{"error": err.Error()})
		return
	}

	res := make(map[string]any)
	content, err := io.ReadAll(f)
	if err != nil {
		ctx.JSON(500, gin.H{"error": err.Error()})
		return
	}

	res["content"] = string(content)
	ctx.JSON(200, res)
}
